package de.tum.in.elitese.wahlsys.persister;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Generic super class for all PersistanceObjects
 * 
 * @author Christoph Frenzel
 */
public abstract class PersistenceObject {
	/**
	 * Creates an "Insert Into ..." String for the given table, fields and
	 * values
	 * 
	 * @param tableName
	 * @param fields
	 * @param values
	 * @return
	 */
	protected static String createInsertString(String tableName, List<String> fields, List<Object> values) {
		assert fields.size() == values.size() : "fields must be of the same size as values";

		StringBuilder result = new StringBuilder();

		result.append("INSERT INTO ");

		result.append(tableName);

		result.append("(");

		for (String field : fields) {
			result.append(field);
			result.append(" , ");
		}
		// remove last ", "
		result.setLength(result.length() - 2);

		result.append(") VALUES (");

		for (Object field : values) {
			if (field == null) {
				result.append("NULL");
			} else if (field instanceof String) {
				// if object is a String add "'"
				result.append("'");
				result.append(field.toString().trim().replace("'", "''"));
				result.append("'");
			} else if (field instanceof Boolean) {
				// if object is a Boolean convert it
				result.append((Boolean) field ? "1" : "0");
			} else if (field instanceof Date) {
				// if object is a Date convert it
				Calendar date = Calendar.getInstance();
				date.setTime((Date) field);
				result.append("'");
				result.append(date.get(Calendar.YEAR));
				result.append("-");
				result.append(date.get(Calendar.MONTH) + 1);
				result.append("-");
				result.append(date.get(Calendar.DAY_OF_MONTH));
				result.append("'");
			} else {
				result.append(field.toString());
			}
			result.append(" , ");
		}
		// remove last ", "
		result.setLength(result.length() - 2);

		result.append(")");

		return result.toString();
	}

	/**
	 * This method creates the one or more SQL strings to persist the object. If
	 * it is a derived class there will be more than one string. In this case
	 * this method should be overwritten.
	 * 
	 * @return a List of the SQL strings
	 */
	public abstract List<String> getPersistanceStrings();
}
